var express = require('express');
var router = express.Router();
const mysql = require('../utils/mysql')
const jiami = require('../utils/jiami')
const jwt = require('jsonwebtoken')
const { expressjwt } = require('express-jwt')
const upload = require('../utils/upload');
const e = require('express');

const secretKey = 'abc'


/* 用户注册 */
router.post('/userreg', async (req, res) => {
  //获取客户端发送的数据
  const { uid, pwd } = req.body;
  //验证数据的正确性
  if (uid.length < 2 || pwd.length < 2) {
    //这是有问题的
    res.json({
      flag: false,
      msg: '用户名或密码格式不正确'
    })
  } else {
    //数据验证通过
    //验证用户名是否重复
    const [{ count }] = await mysql('select count(*) as count from users where username = ?', [uid]);

    if (count > 0) {
      //有重复
      res.json({
        flag: false,
        msg: '用户名已存在'
      })
    } else {
      //可以正常注册
      await mysql(
        'insert into users (username,password,createTime,updateTime) values (?,?,?,?)',
        [uid, jiami(pwd), new Date(), new Date()]
      );
      res.json({
        flag: true,
        msg: '注册成功'
      })
    }

  }

})



/**
 * 用户登录
 */
router.post('/userLogin', async (req, res) => {
  const { uid, pwd } = req.body;

  if (uid.length < 2 || pwd.length < 2) {
    res.json({
      flag: false,
      msg: '用户名或密码格式不正确',
    })
  } else {
    const result = await mysql('select * from users where username=? and password=?', [uid, jiami(pwd)]);
    if (result.length > 0) {
      res.json({
        flag: true,
        msg: '登录成功',
        data: {
          token: jwt.sign({ username: uid, id: result[0].id }, secretKey, { expiresIn: 60 * 60 * 24 })
        }
      })
    } else {
      res.json({
        flag: false,
        msg: '用户名或密码不正确',
      })
    }
  }
})

router.all('*', expressjwt({
  secret: secretKey,
  algorithms: ['HS256']
}))

// router.all('/getdata', async function (req, res) {
//   res.json({
//     query:req.query,
//     body:req.body,
//   })
// });


// router.post('/upload',upload.fields([
//   { name:'pic' },
//   { name:'img' }
// ]),function(req,res){
//   res.json({
//     files:req.files,
//     body:req.body,
//     // params:req.params,
//     // auth:req.auth
//   })
// })

//获取已登录用户信息接口
router.get('/getUserInfo', async function (req, res) {
  //获取当前用户信息
  //获取当前用户id
  const userid = req.auth.id;
  //判断userinfo表中有没有对应记录
  const user = await mysql('select * from userinfo where userid = ?', [userid])
  if (user.length > 0) {
    res.json({
      flag: true,
      data: user[0]
    })
  } else {
    //如果没找到 插入数据
    const newUser = await mysql('insert into userinfo (createTime,updateTime,userid) values (now(),now(),?)', [userid]);
    res.json({
      flag: true,
      data: {}
    })
  }
})


/**
 * 更新用户信息接口
 */
router.post('/updateUserInfo', upload.single('avatar'), async function (req, res) {

  //获取数据
  let { nickname, gender, birthday } = req.body;
  //开始为空
  let avatar = '';
  // 判断值如果为真则取值
  if (req.file) {
    avatar = req.file.destination.slice(6) + req.file.filename
  }

  let userid = req.auth.id;

  //更新数据库
  const arrField = [];
  const arrValues = [];

  arrField.push('nickname=?')
  arrValues.push(nickname)

  // 判断
  if (gender) {
    arrField.push('gender=?')
    if (gender.value == 'male') {
      arrValues.push(false)
    } else {
      arrValues.push(true)
    }
  }
  if (birthday) {
    arrField.push('birthday=?')
    arrValues.push(new Date(birthday))
  }
  if (avatar) {
    arrField.push('avatar=?')
    arrValues.push(avatar)
  }
  arrValues.push(userid)



  let sql = 'update userinfo set updateTime=now(),';
  sql += arrField.join(',')
  sql += ' where userid=?'
  const result = await mysql(sql, arrValues);
  res.json({
    flag: true,
    msg: '更新成功'
  })

})


/**
 * 新增记事本
 */
router.post('/addNote', async function (req, res) {
  const { title, content } = req.body;
  const userid = req.auth.id;
  await mysql(
    'INSERT INTO notebook (title,content,userid) VALUES (?,?,?)',
    [title, content, userid]
  )

  res.json({
    flag: true,
    msg: '发布成功'
  })
})

/**
 * 查询记事本
 */
router.get('/getNote', async function (req, res) {
  const userid = req.auth.id;

  let { search_string, page, per_page } = req.query;

  if (!search_string) {
    search_string = ''
  }

  page = Number(page);
  if (Number.isNaN(page)) {
    page = 1
  } else {
    if (page < 1) {
      page = 1;
    }
  }

  per_page = Number(per_page);
  if (Number.isNaN(per_page)) {
    per_page = 15
  } else {
    if (per_page < 10) {
      per_page = 2;
    }
  }

  const result = await mysql('select * from notebook where title like ? and userid = ? order by updateTime desc limit ?,?',
    ['%' + search_string + '%', userid, (page - 1) * per_page, per_page]);

  const [{ count: total }] = await mysql('select count(*) as count from notebook where title like ? and userid = ?',
    ['%' + search_string + '%', userid])
  res.json({
    flge: true,
    data: {
      list: result,
      total: total,
      pageSize: per_page
    }
  });
})


module.exports = router;
